package cn.zysheep.service.impl;

/**
 * @version v1.0
 * @Author: lyw
 * @Date: 2021/7/26
 */

import cn.zysheep.entity.PermissionDto;
import cn.zysheep.entity.UserDto;
import cn.zysheep.mapper.PermissionMapper;
import cn.zysheep.mapper.UserMapper;
import cn.zysheep.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Log4j2
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDto> implements UserService, UserDetailsService {

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录的账号:{}",username);
        //根据账号去数据库查询
        QueryWrapper<UserDto> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        UserDto userDto = userMapper.selectOne(queryWrapper);

        if (userDto == null){
            throw new UsernameNotFoundException("用户名不存在!");
        }

        //获取用户所有权限
        List<PermissionDto> permissionDtos = permissionMapper.findAllByUserId(userDto.getId());

        ArrayList<SimpleGrantedAuthority> simpleGrantedAuthorities = new ArrayList<>();
        permissionDtos.forEach(permissionDto->{
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permissionDto.getCode());
            simpleGrantedAuthorities.add(simpleGrantedAuthority);
        });


        //权限使用静态数据，后面去查数据库
        UserDetails userDetails = User.withUsername(userDto.getFullname())
                .password(userDto.getPassword())
                .authorities(simpleGrantedAuthorities)
                .build();

        return userDetails;
    }
}
